package com.biwano.swapmyjob.beans;

import java.io.IOException;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;



public class BaseBean {

	public static final int maxStringSize = 100;


	public enum RETURNVALUE
	{
		success,error,gotohome,gotoregisterpage,unhandlederror,registersuccess;
	}
	
	public static void addErrorBE(String target, String message) {

		FacesContext.getCurrentInstance()
				.addMessage(
						target,
						new FacesMessage(FacesMessage.SEVERITY_ERROR, message,
								message));
	}
	public static void addError(String target, String bundle, String key) {
			addErrorBE(target,getErrorText(bundle,key));
	}

	public static boolean hasErrors() {
		for (FacesMessage m : FacesContext.getCurrentInstance()
				.getMessageList()) {
			if (m.getSeverity() == FacesMessage.SEVERITY_ERROR
					|| m.getSeverity() == FacesMessage.SEVERITY_FATAL)
				return true;
		}
		return false;
	}
	
	public static Object evaluateEL(String el) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ELContext elContext = facesContext.getELContext();
		ExpressionFactory expressionFactory = facesContext.getApplication()
				.getExpressionFactory();
		ValueExpression exp = expressionFactory.createValueExpression(
				elContext, el, Object.class);
		return exp.getValue(elContext);
	}
	public static String getErrorText(String bundle, String key)
	{
		return getText(bundle,"error_" + key);
	}
	public static String getLabelText(String bundle, String key)
	{
		return getText(bundle,"label_" + key);
	}
	public static String getText(String bundle, String key)
	{
		return getBundleText(bundle+"Text", key );
	}
	public static String getBundleText(String bundle, String key)
	{
		return (String)evaluateEL("#{"+bundle+"."+key+"}");
	}
	public static void redirect(String url)
	{
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
